import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts';

/**
 * @method BarStackChart
 **/
export default function BarStackChart({
  width = 1000,
  height = 500,
  dataSource,
  id = 'bar',
  xAxisKey,
  dataKey,
  dataRender = null,
  xRender = null,
  isDd = false,
  colors,
  legendSetting = {},
  barWidth = 'auto',
  seriesTop = 0,
  colorOptions = [
    '#c23531',
    '#2f4554',
    '#61a0a8',
    '#d48265',
    '#91c7ae',
    '#749f83',
    '#ca8622',
    '#bda29a',
    '#6e7074',
    '#546570',
    '#c4ccd3',
  ],
}) {
  const chart = useRef(null);
  useEffect(() => {
    const xAxis =
      dataSource &&
      dataSource[0] &&
      dataSource[0] &&
      dataSource[0].value &&
      dataSource[0].value.map((item) => (xRender ? xRender(item) : item[xAxisKey]));

    const _series = dataSource.map((it) => {
      return {
        name: it.name,
        type: 'bar',
        stack: isDd ? '总量' : it.name,
        data: it.value && it.value.map((it) => (dataRender ? dataRender(it) : it[dataKey])),
        barWidth: barWidth,
        top: seriesTop,
      };
    });
    chart.current = echarts.init(document.getElementById(id));
    chart.current.setOption({
      color: colorOptions,
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          // 坐标轴指示器，坐标轴触发有效
          type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
        },
      },
      legend: {
        data: dataSource.map((it) => it.name),
        padding: [20, 0, 0, 0],
        textStyle: {
          color: colors ? colors[0] : '#333',
        },
        ...legendSetting,
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: xAxis,
        axisLabel: {
          textStyle: {
            color: colors ? colors[0] : '#333',
          },
        },
        axisLine: {
          lineStyle: {
            color: colors ? colors[1] : '#333',
          },
        },
      },
      yAxis: {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: colors ? colors[0] : '#333',
          },
        },
      },
      series: _series,
    });
  }, [dataSource]);

  useEffect(() => {
    window.addEventListener('resize', () => {
      chart.current && chart.current.resize();
    });
    return () => {
      window.removeEventListener('resize', () => {
        chart.current && chart.current.resize();
      });
    };
  }, []);

  return <div id={id} style={{ width: width, height: height }} />;
}
